//Get and use stats with JSON
var asteroid_dens = {};

$(document).ready(function(){

	$.getJSON("http://localhost:8080/get_turn",function(data){
		set_turn(data.turn.toString());
	});
	
	
	$.getJSON("http://localhost:8080/get_game_info",function(data){
		var a = 0;
		
		for (var i in data.space_items)
		{
			item = data.space_items[i];
			
			
			if(item['type'] == 'asteroid')
			{
				a += 1;
				
			}
			
			if(item['type'] == 'base')
			{
				$("#bases").append("<li>Player: "+
						item.player+", Ore: "+
						item.ore+", Ships: "+
						item.ship+", "+
						item.x+", "+
						item.y+", "+
						"</li>");
			}
			
			if(item['type'] == 'ship')
			{
				$("#ships").append('<br>' + object_2_string(item));
			}

		}
		
		$("#ass_count").html('Ass Count = ' + a);
	});
	
	$.getJSON("http://localhost:8080/get_turn",function(data){
		set_turn(data.turn.toString());
	});
	
	var view = get_player_view(2);
	$("#view_ass_count").html('View Ass Count = ' + view.items.asteroids.length);
	
	asteroid_dens = calc_ass_dens(view.items.asteroids);
	console.log('foo1');
	console.log(object_2_string(asteroid_dens));
	console.log('foo2');
	
});

function set_turn(turn)
{
	$('#turn').html(turn);
}

function object_2_string(o)
{
	var str = '';
	for(var i in o)
	{
		str += i + ':' + o[i].toString() + ' ';
	}
	return str;
}

function calc_ass_dens(asteroids){
	
	var density = {};
	for(var a in asteroids){
		var cellx = Math.floor(asteroids[a].x/100);
		var celly = Math.floor(asteroids[a].y/100);
		var cell = '(' + cellx + ',' + celly +')';
		if (density[cell])
		{
			density[cell] += 1;
		}
		else
		{
			density[cell] = 1;
		}
		
	}
	return density;
}
